﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Ext.Net;
using Viewer.BusinessObject.BusinessEntities;

namespace Viewer.PhanQuyen.UserControls
{
    public partial class NhomQuyenByToChuc : System.Web.UI.UserControl
    {
        private enum DialogType
        { 
            AddNew,
            Edit,
            Detail
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ResourceManager.GetInstance().RegisterIcon(Icon.Group);
            }
        }

        /// <summary>
        /// Show Add New Dialog
        /// </summary>
        public void ShowAddNewDialog()
        {
            SetUpAddNewDialog();
        }
       
        /// <summary>
        /// SetUp control,bind data in the Add New form before show
        /// </summary>
        /// 
        private void SetUpAddNewDialog()
        {
            this.__DialogType.Text = DialogType.AddNew.ToString();
            this.NhomQuyenByToChucId = 0;
            this.wdAddNew.Title = "Tạo mới nhóm quyền theo tổ chức";
            this.wdAddNew.Icon = Icon.Add;

            this.txtTenNhomQuyenByToChuc.Hidden = false;
            this.txtGhiChu.Hidden = false;

            this.txtTenNhomQuyenByToChuc.Text = string.Empty;
            this.txtGhiChu.Text = string.Empty;

            this.lblTenNhomQuyenByToChuc.Text = string.Empty;
            this.lblGhiChu.Text = string.Empty;

            this.storeNguoiDung_NhomQuyenByToChuc.RemoveAll();
            //grid nguoidung
            btnShowDialogAddNguoiDung.Disabled = false;
            //
            this.txtTenUserOwner.Text = HttpContext.Current.User.Identity.Name;

            ucQUNguoiDung.BindData();
            BuildTreeToChuc();
            this.btnSave.Disabled = false;
            wdAddNew.Show();
        }

        /// <summary>
        /// Show Edit Dialog
        /// </summary>
        /// <param name="pNhomQuyenByToChucId"></param>
        public void ShowEditDialog(int pNhomQuyenByToChucId)
        {
            SetUpEditDialog(pNhomQuyenByToChucId);
        }
        /// <summary>
        /// 
        /// </summary>
        private void SetUpEditDialog(int pNhomQuyenByToChucId)
        {
            this.__DialogType.Text = DialogType.Edit.ToString();
            this.NhomQuyenByToChucId = pNhomQuyenByToChucId;
            this.wdAddNew.Title = "Sửa nhóm quyền theo tổ chức";
            this.wdAddNew.Icon = Icon.ApplicationEdit;
            var oQUNhomQuyenByToChuc = new QUNhomQuyenByToChuc();
            oQUNhomQuyenByToChuc = oQUNhomQuyenByToChuc.GetById(pNhomQuyenByToChucId);
            //Bind data into Detail Area
            this.txtTenNhomQuyenByToChuc.Hidden = false;
            this.txtGhiChu.Hidden = false;

            this.txtTenNhomQuyenByToChuc.Text = oQUNhomQuyenByToChuc.TenNhomQuyenByToChuc;
            this.txtGhiChu.Text = oQUNhomQuyenByToChuc.GhiChu;

            this.lblTenNhomQuyenByToChuc.Text = string.Empty;
            this.lblGhiChu.Text = string.Empty;
            //Grid NguoiDung
            btnShowDialogAddNguoiDung.Disabled = false;
            //

            this.txtTenUserOwner.Text = oQUNhomQuyenByToChuc.TenUserOwner;

            var oQUNguoiDung = new BusinessObject.BusinessEntities.QUNguoiDung();
            this.storeNguoiDung_NhomQuyenByToChuc .DataSource  = oQUNguoiDung.GetBy_NguoiDungByToChucId(NhomQuyenByToChucId);
            this.storeNguoiDung_NhomQuyenByToChuc.DataBind();
            ucQUNguoiDung.BindData();
            BuildTreeToChuc();
            this.btnSave.Disabled = false;
            wdAddNew.Show();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="pNhomQuyenByToChucId"></param>
        public void ShowDetailDialog(int pNhomQuyenByToChucId)
        {
            SetUpDetailDialog(pNhomQuyenByToChucId);
        }
        /// <summary>
        /// 
        /// </summary>
        private void SetUpDetailDialog(int pNhomQuyenByToChucId)
        {
            this.__DialogType.Text = DialogType.Detail.ToString();
            this.NhomQuyenByToChucId = pNhomQuyenByToChucId;
            this.wdAddNew.Title = "Chi tiết nhóm quyền theo tổ chức";
            this.wdAddNew.Icon = Icon.Information;
            var oQUNhomQuyenByToChuc = new QUNhomQuyenByToChuc();
            oQUNhomQuyenByToChuc = oQUNhomQuyenByToChuc.GetById(pNhomQuyenByToChucId);
            //Bind data into Detail Area
            this.txtTenNhomQuyenByToChuc.Hidden=true;
            this.txtGhiChu.Hidden = true;
            this.lblTenNhomQuyenByToChuc.Text = oQUNhomQuyenByToChuc.TenNhomQuyenByToChuc;
            this.lblGhiChu.Text = oQUNhomQuyenByToChuc.GhiChu;
            //Grid Nguoidung
            btnShowDialogAddNguoiDung.Disabled = true;
            //
            var oQUNguoiDung = new BusinessObject.BusinessEntities.QUNguoiDung();
            this.storeNguoiDung_NhomQuyenByToChuc.DataSource = oQUNguoiDung.GetBy_NguoiDungByToChucId(NhomQuyenByToChucId);
            this.storeNguoiDung_NhomQuyenByToChuc.DataBind();
            this.txtTenUserOwner.Text = oQUNhomQuyenByToChuc.TenUserOwner;
            //ucQUNguoiDung.BindData();
            BuildTreeToChuc();
            //Hidden Save button
            this.btnSave.Disabled = true;
            wdAddNew.Show();
        }

        /// <summary>
        /// Save Data Method
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void SubmitNodes(object sender, SubmitEventArgs e)
        {
            if (this.__DialogType.Text == DialogType.AddNew.ToString())
            {
                SaveNewData(e);
                wdAddNew.Hide();
            }
            else if (this.__DialogType.Text == DialogType.Edit.ToString())
            {
                SaveEditData(e);
                wdAddNew.Hide();
            }

        }

      

        private void SaveNewData(SubmitEventArgs e)
        {
            string[] separator = new string[] { "," };
            var NguoiDungIds = this.__NguoiDungIds.Text.Split(separator, StringSplitOptions.RemoveEmptyEntries);
            //AddNew
            var oQUNhomQuyenByToChuc = new BusinessObject.BusinessEntities.QUNhomQuyenByToChuc();
            oQUNhomQuyenByToChuc.TenNhomQuyenByToChuc = this.txtTenNhomQuyenByToChuc.Text.Trim();
            oQUNhomQuyenByToChuc.GhiChu = this.txtGhiChu.Text.Trim();
            oQUNhomQuyenByToChuc.TenUserOwner = this.txtTenUserOwner.Text;
            oQUNhomQuyenByToChuc.UserIDOwner = new Viewer.BusinessObject.BusinessEntities.QUNguoiDung().SearchNguoiDung(this.txtTenUserOwner.Text)[0].NguoiDungID;

            foreach (var strId in NguoiDungIds)
            {
                var oNhomQuyenByToChuc_NguoiDung = new BusinessObject.BusinessEntities.QUNhomQuyenByToChuc_NguoiDung();
                oNhomQuyenByToChuc_NguoiDung.NguoiDungID = int.Parse(strId);
                oQUNhomQuyenByToChuc.QUNhomQuyenByToChuc_NguoiDungs.Add(oNhomQuyenByToChuc_NguoiDung);
            }

            var lstNhomQuyenByToChuc_ToChuc = new List<BusinessObject.BusinessEntities.QUNhomQuyenByToChuc_ToChuc>();
            ReadNode(e.RootNode, lstNhomQuyenByToChuc_ToChuc);
            foreach (var item in lstNhomQuyenByToChuc_ToChuc)
            {
                oQUNhomQuyenByToChuc.QUNhomQuyenByToChuc_ToChucs.Add(item);
            }
            oQUNhomQuyenByToChuc.Save();
            //Update GridParent
            //Close window
            ((PagePhanQuyenByToChuc)this.Page).BindData_NhomQuyenByToChuc();
           
        }

        /// <summary>
        /// Read data from submittedNode of TreeGrid
        /// </summary>
        /// <param name="Node"></param>
        /// <param name="lstItems"></param>
        private void ReadNode(SubmittedNode Node, List<BusinessObject.BusinessEntities.QUNhomQuyenByToChuc_ToChuc> lstItems)
        {

            if (Node.Attributes.Count > 0)
            {
                BusinessObject.BusinessEntities.QUNhomQuyenByToChuc_ToChuc item = new BusinessObject.BusinessEntities.QUNhomQuyenByToChuc_ToChuc();
                item.ToChucID = int.Parse(Node.Text);
                item.IsView = bool.Parse(Node.Attributes["IsView"].ToString());
                item.IsAdd = bool.Parse(Node.Attributes["IsAdd"].ToString());
                item.IsEdit = bool.Parse(Node.Attributes["IsEdit"].ToString());
                item.IsDelete = bool.Parse(Node.Attributes["IsDelete"].ToString());
                item.IsToChucConThuaKe = bool.Parse(Node.Attributes["IsModuleConThuaKe"].ToString());

                item.IsQuyenView = bool.Parse(Node.Attributes["IsQuyenView"].ToString());
                item.IsQuyenAdd = bool.Parse(Node.Attributes["IsQuyenAdd"].ToString());
                item.IsQuyenEdit = bool.Parse(Node.Attributes["IsQuyenEdit"].ToString());
                item.IsQuyenDelete = bool.Parse(Node.Attributes["IsQuyenDelete"].ToString());

                if (item.IsView || item.IsAdd || item.IsEdit || item.IsDelete || item.IsToChucConThuaKe)
                {
                    lstItems.Add(item);
                }

            }

            if (Node.Children.Count > 0)
            {
                foreach (var oItem in Node.Children)
                {
                    ReadNode(oItem, lstItems);
                }
            }
        }

        /// <summary>
        /// Show AddNguoiDung Dialog
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnShowDialogAddNguoiDung_Click(object sender, DirectEventArgs e)
        {
            ucQUNguoiDung.ShowDialog();
        }

        private void BuildTreeToChuc()
        {
            List<NSToChuc> lstToChuc = new List<NSToChuc>();
            lstToChuc = (new NSToChuc()).GetAll();

            var lstToChucLv1 = (from oToChuc in lstToChuc
                                where oToChuc.ToChucLevel == 1
                                select oToChuc).ToList();

            TreeNode nodeToChuc = new TreeNode("ToChuc");
            treeToChuc.Root.Add(nodeToChuc);
            nodeToChuc.Expanded = true;
            foreach (var oToChucLv1 in lstToChucLv1)
            {
                //Create Node
                var nodeLv1 = CreateNode(oToChucLv1);
                nodeToChuc.Nodes.Add(nodeLv1);
            
                

                var lstToChucLv2 = (from oToChuc in lstToChuc
                                    where oToChuc.ToChucLevel == 2 && oToChuc.ToChucIDCha == oToChucLv1.ToChucID
                                    select oToChuc).ToList();
                if (lstToChucLv2.Count == 0)
                {
                    nodeLv1.Leaf = true;
                }
                else
                {
                }

                foreach (var oToChucLv2 in lstToChucLv2)
                {
                    var nodeLv2 = CreateNode(oToChucLv2);
                    nodeLv1.Nodes.Add(nodeLv2);
                    
                    var lstToChucLv3 = (from oToChuc in lstToChuc
                                        where oToChuc.ToChucLevel == 3 && oToChuc.ToChucIDCha == oToChucLv2.ToChucID
                                        select oToChuc).ToList();

                    if (lstToChucLv3.Count == 0)
                    {
                        nodeLv2.Leaf = true;
                    }
                    else
                    {
                    }
                    foreach (var oToChucLv3 in lstToChucLv3)
                    {
                        nodeLv2.Nodes.Add(CreateNode(oToChucLv3));
                    }
                }
            }
            //Render to client
            Ext.Net.X.AddScript(string.Format("refreshTree({0},{1});", treeToChuc.ClientID, treeToChuc.Root.ToJson()));
        }

        private TreeNode CreateNode(NSToChuc oNSToChuc)
        {

            TreeNode oNode = new TreeNode(oNSToChuc.ToChucID.ToString(), Icon.Group);
            //Bind data to "Is View...
            var oQUNhomQuyenByToChuc_ToChuc = (from item in ListQUNhomQuyenByToChuc_ToChuc
                                               where item.ToChucID == oNSToChuc.ToChucID
                                               select item).FirstOrDefault();
            var IsView = false;
            var IsAdd = false;
            var IsEdit = false;
            var IsDelete = false;
            var IsModuleConThuaKe = false;

            if (oQUNhomQuyenByToChuc_ToChuc != null)
            {
                IsView = oQUNhomQuyenByToChuc_ToChuc.IsView;
                IsAdd = oQUNhomQuyenByToChuc_ToChuc.IsAdd;
                IsEdit = oQUNhomQuyenByToChuc_ToChuc.IsEdit;
                IsDelete = oQUNhomQuyenByToChuc_ToChuc.IsDelete;
                IsModuleConThuaKe = oQUNhomQuyenByToChuc_ToChuc.IsToChucConThuaKe;
            }
            //check quyen user tren to chuc do
            QUNhomQuyenByToChuc_ToChuc quyenByToChuc = new QUNhomQuyenByToChuc_ToChuc().GetQuyenByToChucIDandUserID(oNSToChuc.ToChucID, Viewer.BusinessObject.BusinessEntities.QUNguoiDung.GetByUserName(HttpContext.Current.User.Identity.Name).NguoiDungID);

            oNode.CustomAttributes.Add(new ConfigItem("TenToChuc", oNSToChuc.TenToChucFull, ParameterMode.Value));
            oNode.CustomAttributes.Add(new ConfigItem("IsView", IsView.ToString().ToLower(), ParameterMode.Value));
            oNode.CustomAttributes.Add(new ConfigItem("IsAdd", IsAdd.ToString().ToLower(), ParameterMode.Value));
            oNode.CustomAttributes.Add(new ConfigItem("IsEdit", IsEdit.ToString().ToLower(), ParameterMode.Value));
            oNode.CustomAttributes.Add(new ConfigItem("IsDelete", IsDelete.ToString().ToLower(), ParameterMode.Value));
            oNode.CustomAttributes.Add(new ConfigItem("IsModuleConThuaKe", IsModuleConThuaKe.ToString().ToLower(), ParameterMode.Value));
            oNode.CustomAttributes.Add(new ConfigItem("IsQuyenView", quyenByToChuc.IsQuyenView.ToString().ToLower(), ParameterMode.Value));
            oNode.CustomAttributes.Add(new ConfigItem("IsQuyenAdd", quyenByToChuc.IsQuyenAdd.ToString().ToLower(), ParameterMode.Value));
            oNode.CustomAttributes.Add(new ConfigItem("IsQuyenEdit", quyenByToChuc.IsQuyenEdit.ToString().ToLower(), ParameterMode.Value));
            oNode.CustomAttributes.Add(new ConfigItem("IsQuyenDelete", quyenByToChuc.IsQuyenDelete.ToString().ToLower(), ParameterMode.Value));
            oNode.CustomAttributes.Add(new ConfigItem("IsAccess", (IsView && IsAdd && IsEdit && IsDelete).ToString(), ParameterMode.Value));

            oNode.Disabled = !(quyenByToChuc.IsQuyenAdd || quyenByToChuc.IsQuyenView || quyenByToChuc.IsQuyenEdit || quyenByToChuc.IsQuyenDelete);
            oNode.Expanded = true;
            return oNode;
        }

        private List<QUNhomQuyenByToChuc_ToChuc> _lstQUNhomQuyenByToChuc_ToChuc;
        public List<QUNhomQuyenByToChuc_ToChuc> ListQUNhomQuyenByToChuc_ToChuc
        {
            get
            {
                if (_lstQUNhomQuyenByToChuc_ToChuc == null)
                {
                    _lstQUNhomQuyenByToChuc_ToChuc = (new QUNhomQuyenByToChuc_ToChuc()).GetByNhomQuyenByToChucId(this.NhomQuyenByToChucId);

                }
                return _lstQUNhomQuyenByToChuc_ToChuc;
            }
        }

        protected int NhomQuyenByToChucId
        {
            get
            {
                return int.Parse(this.__NhomQuyenByToChucId.Text);
            }
            set
            {
                this.__NhomQuyenByToChucId.Text = value.ToString();
            }
        }

        private void SaveEditData(SubmitEventArgs e)
        {
            string[] separator = new string[] { "," };
            var NguoiDungIds = this.__NguoiDungIds.Text.Split(separator, StringSplitOptions.RemoveEmptyEntries);
            //AddNew
            var oQUNhomQuyenByToChuc = (new BusinessObject.BusinessEntities.QUNhomQuyenByToChuc()).GetById(this.NhomQuyenByToChucId);
            oQUNhomQuyenByToChuc.TenNhomQuyenByToChuc = this.txtTenNhomQuyenByToChuc.Text.Trim();
            oQUNhomQuyenByToChuc.GhiChu = this.txtGhiChu.Text.Trim();
            oQUNhomQuyenByToChuc.UserIDOwner = new Viewer.BusinessObject.BusinessEntities.QUNguoiDung().SearchNguoiDung(this.txtTenUserOwner.Text)[0].NguoiDungID;

            oQUNhomQuyenByToChuc.QUNhomQuyenByToChuc_NguoiDungs.Clear();
            foreach (var strId in NguoiDungIds)
            {
                var oNhomQuyenByToChuc_NguoiDung = new BusinessObject.BusinessEntities.QUNhomQuyenByToChuc_NguoiDung();
                oNhomQuyenByToChuc_NguoiDung.NguoiDungID = int.Parse(strId);
                oQUNhomQuyenByToChuc.QUNhomQuyenByToChuc_NguoiDungs.Add(oNhomQuyenByToChuc_NguoiDung);
            }

            var lstNhomQuyenByToChuc_ToChuc = new List<BusinessObject.BusinessEntities.QUNhomQuyenByToChuc_ToChuc>();
            ReadNode(e.RootNode, lstNhomQuyenByToChuc_ToChuc);

            oQUNhomQuyenByToChuc.QUNhomQuyenByToChuc_ToChucs.Clear();

            foreach (var item in lstNhomQuyenByToChuc_ToChuc)
            {
                oQUNhomQuyenByToChuc.QUNhomQuyenByToChuc_ToChucs.Add(item);
            }
            oQUNhomQuyenByToChuc.Save();
            ((PagePhanQuyenByToChuc)this.Page).BindData_NhomQuyenByToChuc();
        }

     }
}